package see.battle.adaptor;

import java.util.LinkedList;

import see.battle.Const;
import see.battle.message.BulletMessage;
import see.battle.message.Message;
import see.battle.message.OpponentFocusMessage;
import see.battle.server.Server;

public class LocalAdaptor implements Adaptor {
  Message _m;  
  private boolean _stop = false;
  private LinkedList<Message> _messages = new LinkedList<Message>();
  private Server _server;
 
  public LocalAdaptor(Server server) {
    _server = server;
  }
  public void set_view(int view) {	  
  }
  @SuppressWarnings("static-access")
  public void run() {
    while (true) {
      if (_stop) break;
      _m = _server.getNextMessage();
      while (_m != null) {
        synchronized (_messages) {
          _messages.addLast(_m);
        }
        _m = _server.getNextMessage();
      }
      try {
        Thread.currentThread().sleep(Const.updateDelay);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
  
  public void stop() {
    _stop = true;
  }

  public Message readNextMessage() {
    _m = null;
    synchronized (_messages) {
      if (_messages.size() != 0) {
        _m = _messages.getFirst();
        _messages.removeFirst();
      }
    }
    return _m;
  }

  //@Override
  public void sendBulletMessage(long time, float position, 
      long additionalShipDelay) {
    _server.addMessage(new BulletMessage(time, position, additionalShipDelay));
  }

  //@Override
  public void sendFocusMessage(float focus) {
    _server.addMessage(new OpponentFocusMessage(focus));
  }
}
